package com.example.service;

import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 * @program: demo
 * @description: 逻辑层
 * @author: chen.st
 * @create: 2022-01-13 20:16
 **/
@Service
public class UserService {

    @Autowired
    private UserDao userDao;


    /**
     * 新增和修改
     * @param user
     */
    public void save(User user) {
        String time = new SimpleDateFormat("yyyy-mm-dd").format(new Date());
        user.setCreateTime(time);
        userDao.save(user);
    }

    /**
     * 删除
     * @param id
     */
    public void del(Long id) {
        userDao.deleteById(id);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public User findById(Long id) {
        return userDao.findById(id).orElse(null);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Page<User> findPage(Integer pageNum,Integer pageSize,String name) {
        Sort sort = Sort.by(Sort.Direction.DESC,"create_time");
        PageRequest pageable = PageRequest.of(pageNum - 1, pageSize, sort);
        return userDao.findNameLike(name,pageable);
    }

}
